package com.homegoods.videomodule.ui.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewTreeObserver;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.cyt.chattlibrary.LiveKit;
import com.homegoods.aroutercomment.ARouterPath;
import com.homegoods.videomodule.R;
import com.homegoods.videomodule.databinding.VideoActivityLiveshowBinding;
import com.homegoods.videomodule.model.LiveShowModel;
import com.homegoods.videomodule.ui.fragments.BottomPanelFragment;
import com.homegoods.videomodule.ui.view.LiveShowVideo;
import com.kedll.library.KBaseActivity;
import com.kedll.library.util.GlideApp;
import com.kedll.library.util.MyUtils;
import com.share.sharelibrary.share.ShareData;

import java.util.Random;

import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;

/**
 * @author QiQi
 * @ClassName: LiveShowActivity
 * @date 2018/10/26
 * @description
 */
@Route(path = ARouterPath.PATH_LIVE_SHOW)
public class LiveShowActivity extends KBaseActivity<VideoActivityLiveshowBinding> implements BottomPanelFragment.OnShareListener {

    @Autowired(name = "data")
    public LiveShowModel model;

    private BottomPanelFragment bottomPanel;
    private LiveShowVideo jzvdStd;
    private Random random = new Random();
    private String roomId;

    @Override
    protected int getLayout() {
        return R.layout.video_activity_liveshow;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        ARouter.getInstance().inject(this);

        bottomPanel = (BottomPanelFragment) getSupportFragmentManager().findFragmentById(R.id.bottom_bar);
        jzvdStd = findViewById(R.id.player_surface);
    }

    @Override
    protected void initEvent() {
        LiveKit.addEventHandler(handler);
        startLiveShow();


        onClicked(mBinding.btnClose, o -> {
            finish();
        });
    }

    private void startLiveShow() {
        roomId = "ChatRoom01";
        String liveUrl = model.getVideoUrl();
        joinChatRoom(roomId);
        loadThumb();
        playShow(liveUrl);
    }

    private void joinChatRoom(final String roomId) {
        LiveKit.joinChatRoom(roomId, 2);
    }

    private void loadThumb() {
        supportPostponeEnterTransition();

        GlideApp.with(this)
                .asBitmap()
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .load(model.getImgUrl())
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        jzvdStd.thumbImageView.setImageBitmap(resource);
                        scheduleStartPostponedTransition(jzvdStd.thumbImageView);
                    }
                });

    }

    private void playShow(String liveUrl) {
        Jzvd.setVideoImageDisplayType(Jzvd.VIDEO_IMAGE_DISPLAY_TYPE_ORIGINAL);

        jzvdStd.setUp(new JZDataSource(liveUrl), Jzvd.SCREEN_WINDOW_NORMAL);
        jzvdStd.directPlay();
    }

    private void scheduleStartPostponedTransition(final View shareElement) {
        shareElement.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                shareElement.getViewTreeObserver().removeOnPreDrawListener(this);
                supportStartPostponedEnterTransition();
                return true;
            }
        });
    }

    @Override
    protected void onDestroy() {
        LiveKit.quitChatRoom();
        Jzvd.releaseAllVideos();
        Jzvd.setVideoImageDisplayType(Jzvd.VIDEO_IMAGE_DISPLAY_TYPE_ADAPTER);
        supportFinishAfterTransition();

        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
        MyUtils.setSystemUi(getWindow(), false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Jzvd.clearSavedProgress(this, null);
        Jzvd.goOnPlayOnPause();
        if (isFinishing()) {
            MyUtils.setSystemUi(getWindow(), true);
        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        if (!bottomPanel.onBackAction()) {
            finish();
            return;
        }
    }


    @Override
    public void onShare() {
        new ShareData.Builder()
                .setThumbUrl(model.getImgUrl())
                .setUrl(model.getVideoUrl())
                .setShareType(ShareData.SHARE_VIDEO)
                .builder()
                .startShare();
    }
}
